<template>
  <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
    <!-- 部门名称 -->
    <el-form-item label="部门名称" prop="name">
      <el-input 
        v-model="formData.name" 
        placeholder="请输入部门名称" 
        clearable 
      />
    </el-form-item>

    <!-- 操作按钮 -->
    <el-form-item>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
      <el-button @click="handleReset">重置</el-button>
      <el-button @click="$emit('cancel')">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import request from '@/util/request'
// import request from '@/util/request'
// 定义Props类型
interface Props {
  department?: {
    id?: number
    name: string
  } | null
}

const props = defineProps<Props>()

// 类型定义
interface DepartmentForm {
  name: string
}

const userInfo = sessionStorage.getItem('user');
const user = userInfo ? JSON.parse(userInfo) : null;
// 表单实例
const formRef = ref<FormInstance>()
const formData = reactive({
  id: undefined as number | undefined,
  name: '',
  createUser: user.user.name,
  updateUser: user.user.name,
})
// 验证规则
const formRules = reactive<FormRules<DepartmentForm>>({
  name: [
    { required: true, message: '部门名称不能为空', trigger: ['blur', 'change'] },
    { min: 2, max: 20, message: '名称长度2-20个字符', trigger: ['blur', 'change'] }
  ]
})

// 提交处理
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    const url = formData.id ? 'per/dept/update' : 'per/dept/add'
    const response = await request.post(url, {
      ...formData,
      // createUser: localStorage.getItem('name') || 'system' // 自动填充创建人
    })

    if (response.data.code == 200) {
      ElMessage.success('操作成功')
      handleReset()
      emit('submit-success')
    } else {
      throw new Error(response.data.message || '操作失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '提交失败，请检查数据')
  }
}

// 重置表单
const handleReset = () => {
  formRef.value?.resetFields()
}

watch(() => props.department, (newVal) => {
  if (newVal) {
    formData.id = newVal.id
    formData.name = newVal.name
  } else {
    formData.id = undefined
    formData.name = ''
  }
}, { immediate: true })

// 定义事件
const emit = defineEmits(['submit-success', 'cancel'])
</script>

<style scoped>
.el-form {
  padding: 20px 30px;
}

.el-form-item:last-child {
  margin-top: 30px;
  text-align: right;
}
</style>